<template>
  <div class="user-login-log">
    <ConfigForm
      ref="configForm"
      :formConfig="formConfig"
      :formModel="formModel"
      :formItems="formItems"
      :tableConfig="tableConfig"
    >
    </ConfigForm>
  </div>
</template>

<script>
import ConfigForm from '@comp/ConfigForm/index.vue'
import {
  apiExportOperateLogExcel,
  apiExportOperateLogPdf,
  apiGetOperatorLogList,
  apiGetProjectNoList
} from '@api/account/user'
import { apiGetRoleListByPro } from '@api/project/configItem/role'
import { exportBlob, getFileNameByResponse, unreactive } from '@/utils/util'
import moment from 'moment'
import { mapState } from 'vuex'

export default {
  name: 'ProjectExportLog',
  components: { ConfigForm },
  data () {
    const _this = this
    const formModel = {
      account: '',
      roleName: '',
      platform: '',
      operateModule: '',
      operateTime: []
    }
    const formItems = unreactive([
      {
        label: this.$t('all.autotext437'),
        key: 'account'
      },
      {
        label: this.$t('all.autotext378'),
        key: 'roleName',
        type: 'select',
        props: () => {
          return {
            allowClear: true,
            options: _this.roleTypeList
          }
        }
      },
      {
        label: this.$t('all.autotext1120'),
        key: 'platform',
        type: 'select',
        props: {
          allowClear: true,
          options: [
            {
              key: 'PC',
              value: 'PC'
            },
            {
              key: this.$t('all.autotext1317'),
              value: this.$t('all.autotext1317')
            }
          ]
        }
      },
      {
        label: this.$t('all.autotext514'),
        key: 'operateModule'
      },
      {
        label: this.$t('all.autotext578'),
        key: 'operateTime',
        type: 'dateRangePicker',
        props: {
          valueFormat: 'YYYY-MM-DD',
          disabledDate: (current) => {
            return current > moment().endOf('day')
          }
        }
      }
    ])
    const formConfig = unreactive({
      buttons: [
        {
          label: this.$t('all.autotext30'),
          key: 'search',
          props: {
            type: 'primary'
          },
          on: {
            click: () => {
              const table = _this.getTableVm()
              table.refresh()
            }
          }
        },
        {
          label: this.$t('all.autotext340'),
          key: 'reset',
          on: {
            click: () => {
              _this.formModel = {
                account: '',
                roleName: '',
                platform: '',
                operateModule: '',
                operateTime: []
              }
              const table = _this.getTableVm()
              table.refresh(true)
            }
          }
        },
        {
          label: this.$t('all.autotext1014'),
          key: 'export',
          tag: 'a-dropdown',
          dropdownItems: [
            { key: 'Excel', label: 'Excel' },
            { key: 'Pdf', label: 'Pdf' }
          ],
          style: {
            marginLeft: 'auto'
          },
          on: {
            click: (e) => {
              if (e.key === 'Excel') return _this.exportLogExcel()
              if (e.key === 'Pdf') return _this.exportLogPdf()
            }
          }
        }
      ]
    })
    const tableConfig = unreactive({
      data: this.loadData,
      scroll: { x: 1200 },
      columns: [
        {
          title: this.$t('all.autotext334'),
          width: '100px',
          dataIndex: 'id',
          scopedSlots: {
            customRender: 'id',
            render: (h, { index, pagination }) => {
              return (
                <span>{_this.getIndexDesc(index, pagination)}</span>
              )
            }
          }
        },
        {
          title: this.$t('all.autotext437'),
          dataIndex: 'account'
        },
        {
          title: this.$t('all.autotext378'),
          width: '100px',
          dataIndex: 'roleName'
        },
        {
          title: this.$t('all.autotext1120'),
          width: '100px',
          dataIndex: 'platform'
        },
        {
          title: this.$t('all.autotext833'),
          width: '100px',
          dataIndex: 'type'
        },
        {
          title: this.$t('all.autotext514'),
          width: '100px',
          dataIndex: 'operateModule'
        },
        {
          title: this.$t('all.autotext617'),
          dataIndex: 'operateObject',
          customRender: text => (text || '-')
        },
        {
          title: this.$t('all.autotext578'),
          width: '200px',
          dataIndex: 'operateTime'
        },
        {
          title: this.$t('all.autotext1128'),
          width: '100px',
          dataIndex: 'statusStr',
          scopedSlots: {
            customRender: 'statusStr',
            render: (h, { text }) => {
              if (text === this.$t('all.autotext872')) {
                return (<div style='color: #43D882'>· {text}</div>)
              }
              return (<div style='color: #F02F2F'>· {text}</div>)
            }
          }
        },
        {
          title: this.$t('all.autotext1112'),
          dataIndex: 'failReason',
          customRender: text => (text || '-')
        }
      ]
    })
    return {
      formModel,
      formItems,
      formConfig,
      tableConfig,
      roleTypeList: [],
      projectNoList: []
    }
  },
  computed: {
    ...mapState({
      proId: state => state.user.project?.id || ''
    })
  },
  created () {
    this.getRoleTypeList()
    this.getProjectNoList()
  },
  methods: {
    getRoleTypeList () {
      return apiGetRoleListByPro({
        proId: this.proId
      }).then((res = []) => {
        this.roleTypeList = res.map(e => ({
          key: e,
          value: e
        }))
      })
    },
    getProjectNoList (projectNo = '') {
      const params = {
        projectNo
      }
      return apiGetProjectNoList(params).then((res = []) => {
        this.projectNoList = res.map(e => ({
          key: e,
          value: e
        }))
      })
    },
    getRequestParams () {
      const { operateTime, account, roleName, platform, operateModule } = this.formModel
      return {
        proId: this.proId,
        logType: 2, // 日志类型（1-系统 2-项目 3-个人）
        operateTimeStart: operateTime[0],
        operateTimeEnd: operateTime[1] || '',
        type: this.$t('all.autotext1014'), // 导出日志，导出时必传递
        account,
        roleName,
        platform,
        operateModule
      }
    },
    loadData (parameter) {
      const params = Object.assign(parameter, this.getRequestParams())
      return apiGetOperatorLogList(params).then(res => {
        return res
      })
    },
    getIndexDesc (index, pagination) {
      const { total, current, pageSize } = pagination
      const currentItem = (current - 1) * pageSize
      return (total - currentItem - index)
    },
    getTableVm () {
      // todo: 这里获取子表格嵌套太深、耦合性太高，改成 eventBus 获取会更好
      return this.$refs.configForm.getTableVm()
    },
    localExport (response) {
      const { headers, data } = response
      const fileName = getFileNameByResponse(headers)
      exportBlob(fileName, data)
    },
    exportLogExcel () {
      return apiExportOperateLogExcel(this.getRequestParams()).then(this.localExport)
    },
    exportLogPdf () {
      return apiExportOperateLogPdf(this.getRequestParams()).then(this.localExport)
    }
  }
}
</script>

<style scoped lang='less'>
.user-login-log {
  border-radius: 8px;
  background-color: #fff;
}

</style>
